package cn.tedu.springmvc.controller;

import cn.tedu.springmvc.dto.UserRegDTO;
import cn.tedu.springmvc.util.JsonResult;
import cn.tedu.springmvc.vo.UserVO;
import org.springframework.web.bind.annotation.*;

import static cn.tedu.springmvc.util.JsonResult.State.ERR_PASSWORD;
import static cn.tedu.springmvc.util.JsonResult.State.ERR_USERNAME;

//@Controller  //必须是Controller,不可以是其他的注解
@RestController
@RequestMapping("/user")
public class UserController {

    public UserController(){
        System.out.println("UserController.UserController");
    }

    @GetMapping("/npe.do")
    public String npe(String username){
        username.toString();
        return "HAHAHA";
    }


    // http://localhost:8080/springmvc01_war_exploded/user/login.do?username=root&password=123456
    @RequestMapping("/login.do")
    public JsonResult<Void> login(String username,String password){
        System.out.println("username = " + username + ", password = " + password);
        // 假设 admin / 888888 是正确的 用户名 / 密码
        // 判断用户名
        if("admin".equals(username)){
            // 用户名正常，判断密码
            if("88888888".equals(password)){
                // 密码也正确，登录成功
                return JsonResult.ok();
            }else{
                // 密码错误
                String message = "登录失败,密码错误";
                return JsonResult.fail(ERR_PASSWORD,message);
            }
        }else{
            // 用户名不存在
            String message = "登录失败,用户名不存在";
            return JsonResult.fail(ERR_USERNAME,message);
        }
    }

    @RequestMapping("/reg.do")
    public JsonResult<Void> reg(UserRegDTO userRegDto){
        System.out.println("userRegDto = " + userRegDto);
//        JsonResult<Void> jsonResult = new JsonResult<>();
//        jsonResult.setState(JsonResult.State.OK.getValue());
        return JsonResult.ok();

    }

    @GetMapping( "/{id:[0-9]+}/info.do")
    public JsonResult <UserVO> info(@PathVariable Long id){
        System.out.println("id = " + id);
        UserVO userVo = new UserVO();
        userVo.setUsername("chengheng");
        userVo.setPassword("1234567890");
        userVo.setEmail("chengheng@qq.com");
//        JsonResult<UserVO> jsonResult = new JsonResult<>();
//        jsonResult.setState(JsonResult.State.OK.getValue());
//        jsonResult.setData(userVo);
        return JsonResult.ok(userVo);
    }

    @GetMapping( "/{username:[a-zA-Z]+}/info.do")
    public UserVO info(@PathVariable String username){
        System.out.println("username = " + username);
        UserVO userVo = new UserVO();
        userVo.setUsername("chengheng");
        userVo.setPassword("1234567890");
        userVo.setEmail("chengheng@qq.com");
        return userVo;
    }

    @GetMapping( "/list/info.do")
    public UserVO info(){
        System.out.println("正在查询用户列表");
        return null;
    }
}
